package handler

import (
	"context"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"
	"rpc_demo/goods_srv/global"
	"rpc_demo/goods_srv/model"
	"rpc_demo/goods_srv/proto"
)

type BrandServ struct {
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (s *BrandServ) BrandList(ctx context.Context, req *proto.BrandFilterRequest) (*proto.BrandListResponse, error) {
	fmt.Println(1212313)
	var brands []model.Brands
	page := int(req.Pages)
	pageSize := int(req.PagePreNums)
	tx := global.Db.Scopes(Paginate(page, pageSize)).Find(&brands)
	if tx.Error != nil {
		return nil, tx.Error
	}
	var brandInfoResponses []*proto.BrandInfoResponse
	for _, v := range brands {
		brandInfoResponses = append(brandInfoResponses, &proto.BrandInfoResponse{
			Id:   v.ID,
			Name: v.Name,
			Logo: v.Logo,
		})
	}
	var total int64
	global.Db.Model(&model.Brands{}).Count(&total)
	return &proto.BrandListResponse{
		Total: int32(total),
		Data:  brandInfoResponses,
	}, nil
}
func (s *BrandServ) CreateBrand(ctx context.Context, req *proto.BrandRequest) (*proto.BrandInfoResponse, error) {
	var brands model.Brands
	res := global.Db.First(&brands)
	if res.RowsAffected > 0 {
		return nil, status.Errorf(codes.NotFound, "品牌已存在")
	}
	brands.Name = req.Name
	brands.Logo = req.Logo
	brands.Logo = req.Logo
	global.Db.Save(&brands)
	return &proto.BrandInfoResponse{
		Id:   brands.ID,
		Name: brands.Name,
		Logo: brands.Logo,
	}, nil
}
func (s *BrandServ) UpdateBrand(ctx context.Context, req *proto.BrandRequest) (*emptypb.Empty, error) {
	return &emptypb.Empty{}, nil
}
func (s *BrandServ) DeleteBrand(ctx context.Context, req *proto.BrandRequest) (*emptypb.Empty, error) {
	return &emptypb.Empty{}, nil
}
